package com.ruoyi.webs.utils;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Iterator;

public class CheckFileUtils {
    private static Logger log = LoggerFactory.getLogger(CheckFileUtils.class);


    public static final String PROVE_FILE_URL = "provefile";


    public static final String PRINT_FILE_URL = "claimprintfile";


    public static final String SING_FILE_URL = "singimg";


    public static final String FILE_BASE_URL = "/userfiles/";


    public static final String DEL_FILE_URL = "delFileUrl";


    public static final String FILE_URL = "fileUrl";


    public static final String UNIT_FILE_URL = "unitfile";


    public static String getFileUrl() {
        return "/userfiles/" + "/证明文件/";
    }


    public static String getUnitFileUrl() {
        return "/userfiles/" + "/unit/";
    }


    public static String getFileDir() {
        String dir =   "/userfiles/" + "/证明文件/";
       // FileUtils.createDirectory(dir);
        return dir;
    }


    public static String getUnitFileDir() {
        String dir =  "/userfiles/" + "/unit/";
        //FileUtils.createDirectory(dir);
        return dir;
    }


    public static boolean isFile(String source) {
        return (new File(source)).isFile();
    }


    public static boolean isFolder(String source) {
        return (new File(source)).isDirectory();
    }


    public static boolean delFile(String fileName) {
        File file = new File(fileName);
        if (!file.exists()) {
            log.debug(String.valueOf(fileName) + " 文件不存在!");
            return true;
        }
        if (file.isFile()) {
            return deleteFile(fileName);
        }
        return deleteDirectory(fileName);
    }


    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                log.debug("删除文件 " + fileName + " 成功!");
                return true;
            }
            log.debug("删除文件 " + fileName + " 失败!");
            return false;
        }

        log.debug(String.valueOf(fileName) + " 文件不存在!");
        return true;
    }


    public static boolean deleteDirectory(String dirName) {
        String dirNames = dirName;
        if (!dirNames.endsWith(File.separator)) {
            dirNames = String.valueOf(dirNames) + File.separator;
        }
        File dirFile = new File(dirNames);
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            log.debug(String.valueOf(dirNames) + " 目录不存在!");
            return true;
        }
        boolean flag = true;

        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {

            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());

                if (!flag) {
                    break;
                }
            } else if (files[i].isDirectory()) {
                flag = deleteDirectory(files[i]
                        .getAbsolutePath());

                if (!flag) {
                    break;
                }
            }
        }

        if (!flag) {
            log.debug("删除目录失败!");
            return false;
        }

        if (dirFile.delete()) {
            log.debug("删除目录 " + dirName + " 成功!");
            return true;
        }
        log.debug("删除目录 " + dirName + " 失败!");
        return false;
    }


    public static boolean createFile(String descFileName) {
        File file = new File(descFileName);
        if (file.exists()) {
            log.debug("文件 " + descFileName + " 已存在!");
            return false;
        }
        if (descFileName.endsWith(File.separator)) {
            log.debug(String.valueOf(descFileName) + " 为目录，不能创建目录!");
            return false;
        }
        if (!file.getParentFile().exists()) {
            if (!file.getParentFile().mkdirs()) {
                log.debug("创建文件所在的目录失败!");
                return false;
            }
        }


        try {
            if (file.createNewFile()) {
                log.debug(String.valueOf(descFileName) + " 文件创建成功!");
                return true;
            }
            log.debug(String.valueOf(descFileName) + " 文件创建失败!");
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            log.debug(String.valueOf(descFileName) + " 文件创建失败!");
            return false;
        }
    }


    public static boolean createDirectory(String descDirName) {
        String descDirNames = descDirName;
        if (!descDirNames.endsWith(File.separator)) {
            descDirNames = String.valueOf(descDirNames) + File.separator;
        }
        File descDir = new File(descDirNames);
        if (descDir.exists()) {
            log.debug("目录 " + descDirNames + " 已存在!");
            return false;
        }

        if (descDir.mkdirs()) {
            log.debug("目录 " + descDirNames + " 创建成功!");
            return true;
        }
        log.debug("目录 " + descDirNames + " 创建失败!");
        return false;
    }


    public static boolean isImage(MultipartFile file) throws IOException {
        boolean falg = true;
        ImageInputStream iis = ImageIO.createImageInputStream(file.getInputStream());
        Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
        if (!iter.hasNext()) {
            falg = false;
        } else {
            BufferedImage img = ImageIO.read(file.getInputStream());
            if (img == null || img.getWidth(null) <= 0 || img.getHeight(null) <= 0) {
                falg = false;
            }
        }
        iis.close();
        return falg;
    }


    public static AjaxJson fileUpload(String uploadPath, MultipartFile file) throws IllegalStateException, IOException {
        AjaxJson j = new AjaxJson();

        boolean falg = isImage(file);
        if (!falg) {
            j.setSuccess(false);
            j.setMsg("请选择正确的图片!");
            return j;
        }


        Calendar cal = Calendar.getInstance();
        int year = cal.get(1);
        int month = cal.get(2) + 1;
        int day = cal.get(5);

        String fileUrl = String.valueOf(getFileUrl()) + uploadPath + "/" + year + "/" + month + "/" + day + "/";
        String fileDir = String.valueOf(getFileDir()) + uploadPath + "/" + year + "/" + month + "/" + day + "/";

//        if (!file.isEmpty()) {
//
//
//            FileUtils.createDirectory(fileDir);
//            String name = file.getOriginalFilename();
//            String filePath = String.valueOf(fileDir) + name;
//            File newFile = FileUtils.getAvailableFile(filePath, 0);
//            file.transferTo(newFile);
//
//            j.setSuccess(true);
//            j.put("delFileUrl", newFile.getAbsolutePath());
//            j.put("fileUrl", String.valueOf(fileUrl) + newFile.getName());
//        } else {
//            j.setSuccess(false);
//            j.setMsg("请选择正确的图片!");
//            return j;
//        }
        return j;
    }


    public static AjaxJson unitFileUpload(String uploadPath, MultipartFile file) throws IllegalStateException, IOException {
        AjaxJson j = new AjaxJson();

//        boolean falg = isImage(file);
//        if (!falg) {
//            j.setSuccess(false);
//            j.setMsg("请选择正确的图片!");
//            return j;
//        }
//
//        Calendar cal = Calendar.getInstance();
//        int year = cal.get(1);
//        int month = cal.get(2) + 1;
//        int day = cal.get(5);
//        String fileUrl = String.valueOf(getUnitFileUrl()) + uploadPath + "/" + year + "/" + month + "/" + day + "/";
//        String fileDir = String.valueOf(getUnitFileDir()) + uploadPath + "/" + year + "/" + month + "/" + day + "/";
//
//        if (!file.isEmpty()) {
//
//
//            FileUtils.createDirectory(fileDir);
//            String name = file.getOriginalFilename();
//            String filePath = String.valueOf(fileDir) + name;
//            File newFile = FileUtils.getAvailableFile(filePath, 0);
//            file.transferTo(newFile);
//
//
//            try {
//                j = BusinessLicense.businessLicense(newFile.getAbsolutePath());
//            } catch (Exception e) {
//
//                e.printStackTrace();
//            }
//            j.setSuccess(true);
//            j.put("delFileUrl", newFile.getAbsolutePath());
//            j.put("fileUrl", String.valueOf(fileUrl) + newFile.getName());
//        } else {
//            j.setSuccess(false);
//            j.setMsg("请选择正确的图片!");
//            return j;
//        }
        return j;
    }
}